package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocal;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    /**
     * 查询自媒体文章
     * @param wmNewsPageReqDto
     * @return
     */
    public ResponseResult findAll(WmNewsPageReqDto wmNewsPageReqDto) {
        // 效验参数
        if (wmNewsPageReqDto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        wmNewsPageReqDto.checkParam();
        // 确认登录
        WmUser wmUser = WmThreadLocal.getUser();
        if (wmUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 构造分页条件
        IPage page = new Page(wmNewsPageReqDto.getPage(), wmNewsPageReqDto.getSize());
        // 构造查询条件
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        // 状态查询
        if (wmNewsPageReqDto.getStatus() != null){
            wrapper.eq(WmNews :: getStatus, wmNewsPageReqDto.getStatus());
        }
        // 时间查询
        if (wmNewsPageReqDto.getBeginPubDate() != null && wmNewsPageReqDto.getEndPubDate() != null){
            wrapper.between(WmNews :: getPublishTime, wmNewsPageReqDto.getBeginPubDate(), wmNewsPageReqDto.getEndPubDate());
        }
        // 频道查询
        if (wmNewsPageReqDto.getChannelId() != null){
            wrapper.eq(WmNews :: getChannelId, wmNewsPageReqDto.getChannelId());
        }
        // 关键字模糊查询
        if (StringUtils.isNotBlank(wmNewsPageReqDto.getKeyword())){
            wrapper.like(WmNews :: getTitle, wmNewsPageReqDto.getKeyword());
        }
        // 当前登录用户
        wrapper.eq(WmNews :: getUserId, wmUser.getId());
        // 排序
        wrapper.orderByDesc(WmNews :: getCreatedTime);
        // 封装page
        page = page(page, wrapper);
        // 封装返回
        PageResponseResult result = new PageResponseResult(wmNewsPageReqDto.getPage(), wmNewsPageReqDto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    /**
     * 文章发布
     * @param wmNewsDto
     * @return
     */
    public ResponseResult submitNews(WmNewsDto wmNewsDto) {
        // 参数效验
        if (wmNewsDto == null || StringUtils.isBlank(wmNewsDto.getTitle()) || StringUtils.isBlank(wmNewsDto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 确认登录
        WmUser wmUser = WmThreadLocal.getUser();
        if (wmUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 准备WmNews对象
        WmNews wmNews = new WmNews();
        // 属性拷贝
        BeanUtils.copyProperties(wmNewsDto, wmNews);
        wmNews.setUserId(wmUser.getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        // 获取封面图片
        if (wmNewsDto.getImages() != null && wmNewsDto.getImages().size() > 0){
            String image = StringUtils.join(wmNewsDto.getImages(), ",");
            wmNews.setImages(image);
        }
        // 获取封面类型
        if (wmNewsDto.getType() == -1){  // -1表示无法确认封面类型，需要从内容中提取图片来确认
            wmNews.setType(null);
        }
        // 保存或修改文章
        saveOrUpdateWmNews(wmNews);
        // 如果是保存草稿，文章发布结束
        if (wmNewsDto.getStatus() == 0){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        // 不是草稿，建立文章与素材之间的关系
        // 抽取出内容中所有图片的地址
        List<String> imageList = extractImageList(wmNews);   // 存储的是内容图片的url地址
        if (imageList.size() > 0){  // 有图片
            // 获取图片ID
            LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(wrapper.in(WmMaterial::getUrl, imageList));
            List<Integer> ids = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
            // 如果ids长度和imageList长度不一致
            if (ids.size() != imageList.size()){
                throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            // 建立素材和文章的关联关系
            wmNewsMaterialMapper.saveRelation(ids, wmNews.getId(), (short)0);
        }
        // 建立封面图片和素材的关系
        // 处理封面图片的自动识别
        if (wmNewsDto.getType() == -1){
            // 如果内容中图片超过三张
            if (imageList.size() >= 3){
                List<String> collect = imageList.stream().limit(3).collect(Collectors.toList());
                wmNews.setImages(StringUtils.join(collect, ","));
            }else if (imageList.size() > 0){
                wmNews.setType((short)1);
                List<String> collect = imageList.stream().limit(1).collect(Collectors.toList());
                wmNews.setImages(StringUtils.join(collect, ","));
            }else {
                wmNews.setType((short)0);
            }
            this.updateById(wmNews);
        }
        // 获取封面图片的地址
        String images = wmNews.getImages();
        if (StringUtils.isNotBlank(images)){
            // 获取图片路径
            String[] split = images.split(",");
            // 获取图片的ID
            LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(wrapper.in(WmMaterial::getUrl, split));
            List<Integer> ids = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
            if (split.length != ids.size()) {
                throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            wmNewsMaterialMapper.saveRelation(ids, wmNews.getId(), (short)1);
        }

        //开始文章审核，审核通过之后需要将文章(wm_news)同步到(ap_article、ap_article_content、ap_article_content)表中
        // wmNewsAutoScanService.autoScanWmNews(wmNews.getId());

        // 将保存的文章wmNews封装成task，发送给leadnews_schedule微服务
        wmNewsTaskService.saveTask(wmNews);


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 抽取出内容中所有图片的地址
     * @param wmNews
     */
    private List<String> extractImageList(WmNews wmNews) {
        String content = wmNews.getContent();
        List<String> imageUrlList = new ArrayList<>();
        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if ("image".equals(map.get("type"))){
                imageUrlList.add(map.get("value").toString());
            }
        }
        return imageUrlList;
    }

    /**
     * 保存或修改文章
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        if (wmNews.getId() == null){
            this.save(wmNews);
        }else {
            // 删除文章与素材之间的关系
            LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
            wmNewsMaterialMapper.delete(wrapper.eq(WmNewsMaterial :: getNewsId, wmNews.getId()));
            // 更新文章
            this.updateById(wmNews);
        }
    }

    /**
     * 文章上下架
     * @param wmNewsDto
     * @return
     */
    public ResponseResult dowOrUp(WmNewsDto wmNewsDto) {
        // 效验参数
        if (wmNewsDto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 文章查询
        WmNews wmNews = getById(wmNewsDto.getId());
        if (wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章不存在");
        }
        // 判断文章是否已发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章还未发布，无法上下架");
        }
        // 修改文章上下架
        wmNews.setEnable(wmNewsDto.getEnable().shortValue());
        this.updateById(wmNews);
        // 将文章的article_id和状态发到kafka内
        Map map = new HashMap();
        map.put("articleId",wmNews.getArticleId());
        map.put("enable",wmNewsDto.getEnable());
        kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
